export default class GameEngine {
    constructor(canvasId) {
        this.canvas = document.getElementById(canvasId);
        this.ctx = this.canvas.getContext('2d');
        this.entities = [];
        this.keyStates = {};
        this.mouse = { x: 0, y: 0 };
        this.running = false;

        window.addEventListener('keydown', this.handleKeyDown.bind(this));
        window.addEventListener('keyup', this.handleKeyUp.bind(this));
        window.addEventListener('mousemove', this.handleMouseMove.bind(this));
    }

    addEntity(entity) {
        this.entities.push(entity);
    }

    start() {
        this.running = true;
        const gameLoop = () => {
            if (this.running) {
                this.update();
                this.render();
                requestAnimationFrame(gameLoop);
            }
        };
        gameLoop();
    }

    stop() {
        this.running = false;
    }

    update() {
        this.entities.forEach(entity => {
            if (entity.update) {
                entity.update(this.keyStates, this.mouse);
            }
        });
        this.checkCollisions();
    }

    render() {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.entities.forEach(entity => {
            if (entity.render) {
                entity.render(this.ctx);
            }
        });
    }

    handleKeyDown(event) {
        this.keyStates[event.key] = true;
    }

    handleKeyUp(event) {
        this.keyStates[event.key] = false;
    }

    handleMouseMove(event) {
        const rect = this.canvas.getBoundingClientRect();
        this.mouse.x = event.clientX - rect.left;
        this.mouse.y = event.clientY - rect.top;
    }

    checkCollisions() {
        for (let i = 0; i < this.entities.length; i++) {
            for (let j = i + 1; j < this.entities.length; j++) {
                const entity1 = this.entities[i];
                const entity2 = this.entities[j];
                if (this.isColliding(entity1, entity2)) {
                    if (entity1.onCollision) {
                        entity1.onCollision(entity2);
                    }
                    if (entity2.onCollision) {
                        entity2.onCollision(entity1);
                    }
                }
            }
        }
    }

    isColliding(entity1, entity2) {
        return (
            entity1.x < entity2.x + entity2.width &&
            entity1.x + entity1.width > entity2.x &&
            entity1.y < entity2.y + entity2.height &&
            entity1.y + entity1.height > entity2.y
        );
    }
}    